package ImageCache;

import java.io.FileInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.conn.DefaultClientConnection;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public class ImageGetFromHttp {

private static final String LOG_TAG="ImageGetFromHttp";

public static Bitmap downloadBitmap(String url){
	final HttpClient client=(HttpClient) new DefaultClientConnection();
	final HttpGet getRequest=new HttpGet(url);
	try {
		HttpResponse response=client.execute(getRequest);
		final int statusCode=
				response.getStatusLine().getStatusCode();
		if(statusCode!=HttpStatus.SC_OK){
			Log.w(LOG_TAG, "error"+statusCode+"while retrieving bitmap from"+url);
		return null;
		}
		final HttpEntity entity=response.getEntity();
		if(entity!=null){
			InputStream inputStream=null;
			try {
				inputStream =entity.getContent();
				FlushedInputStream fit=new FlushedInputStream(inputStream);
				return BitmapFactory.decodeStream(fit);
			} finally{
				if(inputStream!=null){
					inputStream.close();
					inputStream=null;
				}
				entity.consumeContent();
			}
		}
	} catch (IOException e) {
		getRequest.abort();
	}catch(IllegalStateException e){
		getRequest.abort();
	}catch(Exception e){
		getRequest.abort();
	}finally{
		client.getConnectionManager().shutdown();
	}
	return null;
}
static class FlushedInputStream extends FilterInputStream{

	public  FlushedInputStream(InputStream inputStream){
		super(inputStream);
	}
	
	@Override
	public long skip(long n) throws IOException {
		long totalBytesSkipped=0L;
		while(totalBytesSkipped<n){
			long bytesSkipped=in.skip(n-totalBytesSkipped);
			if(bytesSkipped==0L){
				int b=read();
				if(b<0){
					break;
				}else{
					bytesSkipped=1;
				}
			}
			totalBytesSkipped+=bytesSkipped;
		}
		return totalBytesSkipped;
		}
	}
}


